package com.ndp.fb.rdb.db.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.model.business.vo.ectemplate.EcElementFilterParam;
import com.ndp.fb.rdb.api.EcTemplateElementRdbService;
import com.ndp.fb.rdb.db.DaoTemplate;
import com.ndp.fb.rdb.db.impl.mapper.DefaultRowMapper;
import com.ndp.fb.rdb.model.EcTemplate;
import com.ndp.fb.rdb.model.EcTemplateElement;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.ectemplate.EcTemplateElementShowResult;
import com.ndp.fb.util.SQLUtil;
import com.ndp.fb.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by infi.he on 2016/4/18.
 */
@Service
public class EcTemplateElementRdbServiceImpl extends DaoTemplate implements EcTemplateElementRdbService {

    @Override
    public Long save(EcTemplateElement obj) {
        return saveResultId(obj);
    }

    @Override
    public List<Long> batchSave(List<EcTemplateElement> list) {
        return batchSaveResultId(list);
    }

    @Override
    public EcTemplateElement findByName(String elementName, Long orgId) {
        String sql = "select * from ec_template_element where element_name = ? and org_id = ?";
        return findOne(sql, new Object[]{elementName, orgId}, DefaultRowMapper.autoRowMapper(EcTemplateElement.class));
    }

    @Override
    public void cover(Long elementId, String imgPath, String imgPreviewPath, String elementContext) {
        String sql  = "update ec_template_element set element_img = ?,element_preview = ?, element_context = ? where 1=1 and id = ? ";
        getJdbcTemplate().update(sql, new Object[]{imgPath, imgPreviewPath, elementContext, elementId});
    }

    @Override
    public EcTemplateElement getEcTemplateElementByid(Long elementId) {
        String sql = "select * from ec_template_element where 1=1 and id = ?";
        return findOne(sql, new Object[]{elementId}, DefaultRowMapper.autoRowMapper(EcTemplateElement.class));
    }

    @Override
    public List<EcTemplateElement> findByIds(List<Long> ids) {
        String sql = "select * from ec_template_element where 1=1 and id in ("+ SQLUtil.appendPlaceholder(ids.size()) +")";
        return getJdbcTemplate().query(sql, ids.toArray(), DefaultRowMapper.autoRowMapper(EcTemplateElement.class));
    }

    @Override
    public EcTemplateElement findByParentCodeAndMajor(Long wefeedid, Long templateId, String parentCode, Boolean isMajor) {
        logger.info("-------------------------------------------------------------");
        logger.info("templateId>>>" + templateId);
        logger.info("parentCode>>>" + parentCode);
        logger.info("isMajor>>>" + (isMajor ? "1" : "0"));
        if (!"A01".equalsIgnoreCase(parentCode)) {
            String sql = "SELECT  " +
                    "	 t4.* " +
                    "from  " +
                    " ec_element_style t1, " +
                    " ec_template_element_style t2, " +
                    " ec_element_style_color_type t3, " +
                    " ec_template_element t4 " +
                    "where t2.element_style_group_id = t1.style_group " +
                    "and t3.element_style_id = t1.id " +
                    "and t4.element_style_id = t1.id " +
                    "and t4.element_color_type_id = t3.element_color_type_id " +
                    "and t4.is_delete = 0 " +
                    "and t4.element_img is not null " +
                    "and t2.template_id = ? " +
                    "and t4.parent_code = ?  " +
                    "and t4.major = ? \n"+
                    "order by t1.id";
            logger.info(" "+sql);
            return findOne(sql, new Object[]{templateId, parentCode, isMajor ? "1" : "0"}, DefaultRowMapper.autoRowMapper(EcTemplateElement.class));
        } else {
            String sql2 = "SELECT DISTINCT logo.*\n" +
                    " from ec_product_logo logo,\n" +
                    "ec_template_element_style t2,\n" +
                    "product_we_feed feed,\n" +
                    "ec_element_style_color_type t3\n" +
                    "where t2.element_style_group_id = logo.element_style_group_id\n" +
                    "and feed.product_id = logo.product_id\n" +
                    "and t3.element_style_id = logo.element_style_id\n" +
                    "and t3.element_color_type_id = logo.element_color_type_id\n" +
                    "and feed.id = ?\n" +
                    "and t2.template_id = ?\n" +
                    "and logo.major = ? \n"+
                    "order by t2.id";
            logger.info(" "+sql2);
            logger.info("-------------------------------------------------------------");
            return findOne(sql2, new Object[]{wefeedid, templateId, isMajor ? "1" : "0"}, DefaultRowMapper.autoRowMapper(EcTemplateElement.class));
        }
    }

    @Override
    public List<EcTemplateElementShowResult> filter(EcElementFilterParam param, Long orgId, boolean isEn) {
        List paramValue = new ArrayList<>();
        StringBuffer sql = new StringBuffer("SELECT a.*, b.code,");
        if(isEn)
            sql.append("b.en_name AS name");
        else
            sql.append("b.name");
        sql.append(" ,b.style_group FROM ec_element_category e, ec_template_element a, ec_color_type t, ec_element_style b, ec_template_element_style c" +
                " WHERE " +
                " e.code = a.parent_code" +
                " AND a.element_style_id = b.id" +
                " AND a.element_color_type_id = t.id" +
                " AND b.style_group = c.element_style_group_id" +
                " AND a.is_delete = 0 AND e.support_element_filter = 1 " +
                " AND a.org_id = ?");
        paramValue.add(orgId);
        if(param.getElementType() != null && param.getElementType() != 0L) {
            sql.append(" AND e.pid= ?");
            paramValue.add(param.getElementType());
        }

        if(param.getTemplateId() != null && param.getTemplateId() != 0L) {
            sql.append(" AND c.template_id= ?");
            paramValue.add(param.getTemplateId());
        }
        //元素层级，根据code 的开头字母区分....
        if(StringUtil.isNotEmpty(param.getElementLevel()) && !"0".equals(param.getElementLevel())) {
            sql.append(" AND b.`code` LIKE ?");
            paramValue.add(param.getElementLevel() + "%");
        }

        if(StringUtil.isNotEmpty(param.getColor())) {
            sql.append(" AND t.`name` = ?");
            paramValue.add(param.getColor());
        }
        sql.append(" ORDER BY b.style_group,b.sort,a.parent_code");

        return getJdbcTemplate().query(sql.toString(), paramValue.toArray(), DefaultRowMapper.autoRowMapper(EcTemplateElementShowResult.class));
    }

    @Override
    public List<EcTemplateElementShowResult> getAllElements(EcElementFilterParam param, Long orgId,Boolean isEn) {
        List paramValue = new ArrayList<>();

        StringBuffer sql = new StringBuffer("SELECT DISTINCT a.id AS d_Id,a.*, n.code,");
        if(isEn) {
            sql.append("n.en_name AS name");
        }else {
            sql.append("n.name");
        }
        sql.append(" , n.style_group FROM ec_element_category e, ec_template_element a, ec_color_type t, " +
                "(SELECT b.* FROM ec_element_style b ORDER BY b.`style_group`,b.sort ");
        if(param.getTPage() >= 2) {
            sql.append("LIMIT ?,?");
            paramValue.add(param.getCPage());
            paramValue.add(param.getPSize());
        }
        sql.append(" )  n WHERE " +
                " e.code = a.parent_code" +
                " AND a.element_style_id = n.id" +
                " AND a.element_color_type_id = t.id" +
                " AND a.is_delete = 0  AND e.support_element_filter = 1 AND a.org_id = ? ");
        //必须按公司隔离
        paramValue.add(orgId);
        if (param.getElementType() != null && param.getElementType() != 0L) {
            sql.append(" AND e.pid= ?");
            paramValue.add(param.getElementType());
        }
        //元素层级，根据code 的开头字母区分....
        if(StringUtil.isNotEmpty(param.getElementLevel()) && !"0".equals(param.getElementLevel())) {
            sql.append(" AND n.`code` LIKE ?");
            paramValue.add(param.getElementLevel() + "%");
        }

        if(StringUtil.isNotEmpty(param.getColor())) {
            sql.append(" AND t.`name` = ?");
            paramValue.add(param.getColor());
        }
        sql.append("  ORDER BY n.style_group,n.sort,a.parent_code");
        return getJdbcTemplate().query(sql.toString(), paramValue.toArray(), DefaultRowMapper.autoRowMapper(EcTemplateElementShowResult.class));
    }



    @Override
    public void updateFillValue(String fillValue, Long id) {
        String sql = "update ec_materiel_elements set fill_value = ? where id = ?";
        getJdbcTemplate().update(sql, new Object[]{fillValue, id});
    }

    @Override
    public void updateContext(String context, Long id) {
        String sql = "update ec_materiel_elements set element_context = ? where id = ?";
        getJdbcTemplate().update(sql,new Object[]{context,id});
    }

    @Override
    public Integer getGroupCount(EcElementFilterParam param) {
        List paramValue = new ArrayList<>();
        StringBuffer sql = new StringBuffer("SELECT COUNT(DISTINCT n.id)  " +
                "FROM ec_element_category e, " +
                "ec_template_element a,  " +
                "ec_color_type t,  " +
                "ec_element_style n " +
                "WHERE e.code = a.parent_code " +
                "    AND a.element_style_id = n.id " +
                "    AND a.element_color_type_id = t.id " +
                "    AND a.is_delete = 0 ");

        if(param.getElementType() != null && param.getElementType() != 0L) {
            sql.append(" AND e.pid= ?");
            paramValue.add(param.getElementType());
        }

        //元素层级，根据code 的开头字母区分....
        if(StringUtil.isNotEmpty(param.getElementLevel()) && !"0".equals(param.getElementLevel())) {
            sql.append(" AND n.`code` LIKE ?");
            paramValue.add(param.getElementLevel() + "%");
        }

        if(StringUtil.isNotEmpty(param.getColor())) {
            sql.append(" AND t.`name` = ?");
            paramValue.add(param.getColor());
        }
        return getJdbcTemplate().queryForInt(sql.toString(),paramValue.toArray());
    }

    @Override
    public List<EcTemplateElementShowResult> findByTemplateIdAndParentCodeAndMajorAndOrgId(Long templateId, String primaryParentCode, boolean major, Long orgId) {
        String sql = "select distinct e.*,c.name as element_color_name, es.code as style_code from ec_template_element_style ts, ec_element_style es, ec_template_element e,ec_color_type c\n" +
                "where ts.element_style_group_id = es.style_group and e.element_style_id = es.id and c.id = e.element_color_type_id\n" +
                "and ts.template_id = ?\n" +
                "and e.org_id = ?\n" +
                "and e.parent_code = ?\n" +
                "and e.major = ?\n";

        return getJdbcTemplate().query(sql, new Object[]{templateId, orgId, primaryParentCode, major}, DefaultRowMapper.autoRowMapper(EcTemplateElementShowResult.class));
    }

    @Override
    public EcTemplateElement findById(Long templateElementId) {
        String sql = "SELECT * from ec_template_element where id = ?";
        return findOne(sql,new Object[]{templateElementId},DefaultRowMapper.autoRowMapper(EcTemplateElement.class));
    }

    @Override
    public EcTemplateElementShowResult findByIdAndTemplateId(Long id, Long templateId) {
        String sql = "select e.*,c.name as element_color_name, es.code as style_code from ec_template_element e,ec_element_style es, ec_template_element_style tes, ec_color_type c\n" +
                "where es.id = e.element_style_id  and tes.element_style_group_id = es.style_group  and e.element_color_type_id = c.id\n" +
                "and e.id = ? and tes.template_id = ?;";
        return findOne(sql,new Object[]{id, templateId},DefaultRowMapper.autoRowMapper(EcTemplateElementShowResult.class));
    }
}
